import React from "react";
import SearchHeader from "../../components/searchHeader";
// 导入antd-mobile组件库
import { Flex, Toast } from "antd-mobile";
// 导入module.css
import styles from "./index.module.css";
// 导入Filter组件
import Filter from "./components/Filter";
// 导入axios
import { API } from "../../utils/api";
// 引入组件HouseItem
import HouseItem from "../../components/HouseItem";
import { BASE_URL } from "../../utils/url";
import {
  List,
  WindowScroller,
  AutoSizer,
  InfiniteLoader
} from "react-virtualized";
// 导入Sticky组件
import Sticky from "../../components/Sticky";
// 导入NoHouse组件
import NoHouse from '../../components/NoHouse'
// 导入获取当前定位城市
import {getCurrentCity} from '../../utils'
// // 获取本地存储中的当期定位城市
// const { label, value } = JSON.parse(localStorage.getItem("city"));
export default class HouseList extends React.Component {
  state = {
    list: [],
    count: 0,
    isLoading: true
  };
  // 初始化label 和 value 值
  label = ''
  value = ''
  // 初始化filters
  filters = {};
  // 获取房屋详细数据
  async getHouseList() {
    this.setState(() => {
      return {
        isLoading: true
      }
    })
    // 开启loading效果
    Toast.loading("Loading...", 0, null, false);
    const { data: res } = await API.get(`/houses`, {
      params: {
        cityId: this.value,
        ...this.filters,
        start: 1,
        end: 20
      }
    });
    // console.log(res);
    const { list, count } = res.body;
    this.setState(() => {
      return {
        list,
        count,
        isLoading: false
      };
    });
    // 关闭loading效果
    Toast.hide();
    // 提示房源数量
    if(count !== 0) {
      Toast.info(`共找到${count}套房源`, 2,null,false);
    }
    
  }
  // 接收Filter组件传过来的数据
  onFilter = filters => {
    this.filters = filters;
    this.getHouseList();
    // 设置每次切换房源条件都回到顶部
    window.scroll(0,0)
  };
  async componentDidMount() {
    const {label,value} = await getCurrentCity()
    // 添加到this中，方便调用
    this.label = label
    this.value = value
    this.getHouseList();
  }
  renderHouseItem = ({
    key, // Unique key within array of rows
    index, // 索引号
    style // 指定每一行的位置
  }) => {
    const { list } = this.state;
    const house = list[index];
    if (!house) {
      return (
        <div key={key} style={style}>
          <p className={styles.bgcColor}></p>
        </div>
      );
    }
    return (
      <HouseItem
        key={key}
        style={style}
        src={BASE_URL + house.houseImg}
        title={house.title}
        desc={house.desc}
        tags={house.tags}
        price={house.price}
        onClick={()=> this.props.history.push(`/detail/${house.houseCode}`)}
      />
    );
  };
  // 判断列表中的每一行是否加载完成
  isRowLoaded = ({ index }) => {
    return this.state.list[index];
  };
  // 用来获取更多房源列表数据
  loadMoreRows = ({ startIndex, stopIndex }) => {
    return new Promise(resolve => {
      // 数据加载完成时，调用res 即可
      // 开启loading效果
      Toast.loading("Loading...", 0, null, false);
      API.get(`/houses`, {
        params: {
          cityId: this.value,
          ...this.filters,
          start: startIndex,
          end: stopIndex
        }
      }).then(val => {
        this.setState(() => {
          return {
            list: [...this.state.list, ...val.data.body.list]
          };
        });
        // 关闭loading效果
        Toast.hide();
        resolve();
      });
    });
  };
  renderHouseList = () => {
    const { count, isLoading } = this.state;
    
    if (count === 0 && !isLoading) {
      return <NoHouse>暂时没有房源，请调整搜索条件~</NoHouse>;
    }
    return (
      <InfiniteLoader
        isRowLoaded={this.isRowLoaded}
        loadMoreRows={this.loadMoreRows}
        rowCount={count}
      >
        {({ onRowsRendered, registerChild }) => (
          <WindowScroller>
            {({ height, isScrolling, scrollTop }) => (
              <AutoSizer>
                {({ width }) => (
                  <List
                    autoHeight //设置高度为WindowScroller 最终渲染的列表高度
                    width={width} //视口宽度
                    height={height} //视口高度
                    rowCount={count} //行数
                    rowHeight={120} //每一行的高度
                    rowRenderer={this.renderHouseItem} //要渲染的内容
                    isScrolling={isScrolling}
                    scrollTop={scrollTop}
                    onRowsRendered={onRowsRendered}
                    registerChild={registerChild}
                  />
                )}
              </AutoSizer>
            )}
          </WindowScroller>
        )}
      </InfiniteLoader>
    );
  };
  render() {
    return (
      <div className={styles.root}>
        <Flex className={styles.header}>
          <i
            className="iconfont icon-back"
            onClick={() => {
              this.props.history.go(-1);
            }}
          />{" "}
          <SearchHeader cityName={this.label} className={styles.searchHeader} />{" "}
        </Flex>{" "}
        {/* Filter组件 */}
        <Sticky height={40}>
          <Filter onFilter={this.onFilter}> </Filter>{" "}
        </Sticky>
        {/* HouseItem */}
          <div className={styles.houseItems}>{this.renderHouseList()}</div>
      </div>
    );
  }
}

